<style lang='scss' scoped>
	.deviceMonitor {
		.device_info {
			font-size: 14px;
			.left {
				width: 50%;
				float: left;
				padding: 10px 0px 0px 10px;
			}
			.device_img {
				width: 100%;
			}
			.right {
				width: 50%;
				float: left;
				padding: 10px;
			}
			.data_list {
				padding-left: 10px;
				line-height: 25px;
			}
		}
		.tree_table {
			padding-left: 10px;
		}
	}
</style>
<style lang='scss'>
	.chart_tab {
		margin: 5px 10px 0px;
		.el-tabs__header {
			margin: 0 0 1px;
		}
		.el-tabs__nav {
			background: #FFFFFF;
			.el-tabs__item {
				height: 30px;
				line-height: 30px;
				padding: 0 10px;
			}
		}
		.el-tabs__nav-prev,
		.el-tabs__nav-next {
			/*background: #42b983;
			color: #FFFFFF;*/
			line-height: 34px;
		}
	}
	
	.deviceMonitor {
		.window_tool {
			top: 15px;
			position: absolute;
			right: 12px;
			z-index: 999;
			font-size: 14px;
			cursor: pointer;
			.minisize {
				top: -3px;
				right: 38px;
				position: absolute;
			}
		}
	}
	
	.maxHeight {
		height: 50vh;
	}
	
	.el-carousel__item h3 {
		color: #475669;
		font-size: 14px;
		opacity: 0.75;
		line-height: 200px;
		margin: 0;
	}
	
	.el-carousel__container {
		height: 100px;
	}
	
	.el-carousel__item:nth-child(2n) {
		background-color: #99a9bf;
	}
	
	.el-carousel__item:nth-child(2n+1) {
		background-color: #d3dce6;
	}
	
	.desc {
		position: absolute;
		top: -50px;
		left: 3px;
		color: #ffffff;
		width: 60px;
	}
</style>
<template>
	<div class='deviceMonitor gridLayout custom-commonBox'>
		<div style="position: relative;">
			<el-form  class="content_search_box main-box"  ref="searchFactor" :model="searchFactor" label-width="85px">
				<div style="display:flex">
					<el-form-item label="测点名称：">
						<el-select v-model='searchFactor.pointIndexs' @change="changePoint()" :collapse-tags='true' multiple filterable v-shift-multi-select clearable style="width:240px">
							<el-option v-for="(item,index) in pointList" :key="index" :label="item.pointName+'('+(item.manuId||'')+')'" :value="index">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item v-if="activeName =='first'" label="数据量：" label-width="80px">
						<el-select  v-model="searchFactor.pageSize" placeholder="请选择" style="width:80px">
							<el-option v-for="(item ,index) in sizeOption" :key="index" :label="item+'条'" :value="item">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="" label-width="10px">
						<el-radio-group  @change="chartList = [];changeQueryType(searchFactor.type)" v-model="searchFactor.type">
							<el-radio label="0">实时监控</el-radio>
							<el-radio label="1">历史监控</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="searchFactor.type==1" label-width="10px">
						<datatime :pointIds="searchFactor.deviceIds" :time="searchFactor.modify_start_time" dataType="tiesan" @changeTime="(time)=>{searchFactor.modify_start_time = time}" :placeholderText="$t('spotMonitor.startDate')" style="width:180px" />
					</el-form-item>
					<el-form-item  v-if="searchFactor.type==1" label-width="5px">
						<datatime :pointIds="searchFactor.deviceIds" :time="searchFactor.modify_end_time" dataType="tiesan" @changeTime="(time)=>{searchFactor.modify_end_time = time}"  :placeholderText="$t('spotMonitor.endDate')" style="width:180px" />
					</el-form-item>
					<el-form-item label-width="10px">
						<el-button class="ml5" type="primary" @click="queryData()">查询</el-button>
					</el-form-item>
				</div>
			</el-form>
			<el-tabs  class="mt5 fl ml10" v-model="activeName">
				<el-tab-pane class="ml5" label="曲线" name="first"></el-tab-pane>
				<el-tab-pane class="ml5" label="表格数据" name="second"></el-tab-pane>
			</el-tabs>
			<screenfull :icon="'el-icon-full-screen'" :elId="'anchor_box'" class="fl ml10" style="font-size: 20px;margin-top:13px"></screenfull>
			<div class="clear_both"></div>
			<div id="anchor_box">
				<div v-if="activeName=='first'">
					<div v-if="chartList.length">
						<el-row  id="anchor_box" class='' style="height: calc(100vh - 235px);overflow: auto;">
							<el-col :span="item.width" :id="'anchor-'+index" v-for="(item,index) in chartList" :key="index" :style="'position:'+layout+';z-index:'+item.zIndex">
								<div class="window_tool">
									<i v-if="(!item.zIndex)||(item.width!=24)" @click="showWindow(item,index)" class="color-primary fa fa-window-maximize"></i>
									<i v-else @click="restoreWindow(item,index);" class="color-primary fa fa-window-restore"></i>
									<i @click="closeWindow(index)" class="color-primary fa fa-window-close-o ml5"></i>
								</div>
								<div style="padding: 5px;position: relative;">
									<div class="main-box col_box">
										<echart v-if="item.newOptions" :ref="'chartRef'+index" :eventKey="index" :options="item.newOptions" :style="'height:'+chartHeight"></echart>
										<div class="next_tip">
											<i @click="prevOrNextClick('prev',item,index)" class="left el-icon-caret-left plus_icon"></i>
											<i @click="prevOrNextClick('next',item,index)" class="right el-icon-caret-right plus_icon"></i>
										</div>
									</div>
								</div>
							</el-col>
						</el-row>
						<div class="mt10" style="width:100%;text-align:center">
							<el-pagination @current-change="handleCurrentChange" :current-page="page" :page-size="size" layout="prev, pager, next" :total="searchFactor.deviceIds.length"></el-pagination>
						</div>
					</div>
					<noData class="main-box" v-else />
				</div>
				<div v-if="activeName == 'second'">
					<gird-data class="" ref="gridChart" :searchFactor="searchFactor" :type="'data'" :pointList="selectPointList" style="height: calc(100vh - 190px);" />
				</div>
			</div>
		</div>
		<div id="menuuu_box" class="menuuu_box" style="display: none;">
			<!-- <div class="title">
				<div class="title_desc">测点信息分析</div>
				<i @click='hiddenMenu' class="el-icon-close icon_cls"></i>
			</div>
			<div class="label_li" @click="showPage='section';analysisModal=true;showModal2= false;hiddenMenu()">
				<svg-icon class="fl icon" icon-class="cedian"></svg-icon>
				<span class="fl">查看截面图</span>
			</div>
			<div class="label_li" @click="showPage='lineAnalysis';analysisModal=true;showModal2= false;hiddenMenu()">
				<svg-icon class="fl icon" icon-class="cedian"></svg-icon>
				<span class="fl">测点与曲线分析</span>
			</div>
			<div class="label_li" @click="updateStatus();hiddenMenu()">
				<svg-icon class="fl icon" icon-class="cedian"></svg-icon>
				<span class="fl">{{currentParams.status == '0'?'标记异常点':'取消异常点'}}</span>
			</div>
			<div class="label_li" @click="updateShowStatus(currentParams.pointId);hiddenMenu()">
				<svg-icon class="fl icon" icon-class="cedian"></svg-icon>
				<span class="fl">{{getPointStatus(currentParams.pointId) == 'show'?'不展示异常测点':'恢复异常点展示'}}</span>
			</div> -->
			<div class="label_li">
				<el-tooltip class="item" effect="dark" content="曲线缩放倍数" placement="top-start">
					<i class="fl el-icon-circle-plus-outline" style="font-size: 18px;"></i>
				</el-tooltip>
				<span class="fl ml5"><el-input-number v-model="magnification" size="mini" controls-position="right" @change="reloadChart(currentParams.chartData,currentParams.chartIndex)" :min="1" style="width: 90px;"></el-input-number></span>
				<span class="fl mt5">缩放倍数</span>
			</div>
		</div>
		<div v-if="showModal2" @click="showModal2 = false;hiddenMenu();" style="position: absolute;width: 100%;height: 100vh;top: 0px;left: 0px;z-index: 9;"></div>
		<el-dialog v-dialogDrag :title="showPage=='section'?'结构图':'测点与曲线分析'" :visible.sync="analysisModal" width="1200px" height="100%" class="line_analysis" top>
			<div v-if="analysisModal">
				<jiemian-chart v-if="showPage == 'section'" :currentParams="currentParams" />
				<line-analysis v-else :currentParams="currentParams" :dataType="1" />
			</div>
		</el-dialog>
		<el-dialog v-dialogDrag title="标记数据" :append-to-body="true" :visible.sync="showStatusModal" width="40%">
			<el-form>
				<el-form-item label="类型" label-width="90">
					<el-radio-group v-model="dataStatus">
						<el-radio label="1">标记为异常点</el-radio>
						<el-radio label="0">取消异常点</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click="showStatusModal = false">取 消</el-button>
				<el-button size="small" type="primary" @click="saveOperateValue()">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	/* eslint-disable */
	import { util ,getPointIds,getPointIndex} from "@/utils/common"
	import { mapGetters } from 'vuex'
	export default {
		name: 'deviceMonitor',
		components: {
  			girdData: () => import('./components/originGirdData'),
		},
		data() {
			let magnification = localStorage.getItem('magnification') || 10
			return {
				sizeOption: util.sizeOption,
				statusObj: util.statusObj,
				statusColor: util.statusColor,
				activeName: 'first',
				magnification: magnification,
				showStatusModal: false,
				dataStatus: '1', //异常点
				updateData: {},
				showModal2: false,
				analysisModal: false,
				showPage: '',
				initInfo: {
					freq: ''
				},
				websock: null,
				stompClient: null,
				searchFactor: {
					pageSize: 500,
					deviceName: '',
					deviceIndex: '',
					projectId: '',
					pointIndexs: [],
					pointIds: [],
					deviceIds: [],
					type: '0', //实时监控
					modify_start_time: '',
					modify_end_time: '',
					isAllData: false //是否查询全部数据
				},
				oldSearchData: {},
				chartList: [],
				chartRef: {},
				currentParams: {},
				pointList: [],
				selectPointList: [],
				fftPhyId: 0,
				fftArr: [],
				subscription: null,
				interObj: {},
				token: util.getToken(),
				routeName: util.getToken() + this.$route.name,
				chartHeight: '280px',
				layout: 'relative',
				scoketConnect: null,
				page:1,
				size:10,
				total:0
			}
		},
		destroyed() {
			// this.$store.commit('SET_SEARCH_INFO',this.searchFactor)
			this.$Bus.$off('realData')
			this.closeConnect();
		},
		computed: {
			// 使用对象展开运算符将 getter 混入 computed 对象中
			...mapGetters([
				'projectInfo',
				'userInfo',
				'secondRouters',
				'searchInfo',
				'theme'
			])
		},
		mounted() {
			this.searchFactor.pageSize = localStorage.getItem('pageSize_' + this.projectInfo.id) || 500
			this.searchFactor.projectId = this.projectInfo.id;
			this.initDeviceList();

			let cacheObj = {
				data1: [],
				data2: [],
				data3: [],
				data4: [],
				data5: []
			};
			// this.$Bus.$on('realData', (item) => {
			// 	//每次渲染几个以40hz为基础
			// 	let freq = this.initInfo.freq && (1000 / (this.initInfo.freq)) || 25,
			// 		renderSize = freq < 25 ? Math.ceil(25 / freq) : 1
			// 	cacheObj[item.data_id + item.phy] = cacheObj[item.data_id + item.phy] || []
			// 	cacheObj[item.data_id + item.phy].push(item)
			// 	Object.keys(cacheObj).forEach(it => {
			// 		let chacheList = cacheObj[it]
			// 		if(!this.interObj[it]) {
			// 			//考虑内存溢出 cacheObj.phy中的数据需截取掉
			// 			if(chacheList.length > 1024) { //超出1024条，截出后面1024条
			// 				cacheObj[it] = cacheObj[it].slice(chacheList.length - 1024, chacheList.length)
			// 			}
			// 			this.interObj[it] = setInterval(() => {
			// 				if(chacheList.length) {
			// 					let renderArr = chacheList.splice(0, renderSize)
			// 					this.addLineData(renderArr)
			// 				}
			// 			}, freq < 25 ? 25 : freq) //大于40hz的每次渲染25/freq后的数据
			// 		}
			// 	})
			// })
			this.$Bus.$on("getProjectInfo", data => {
				let index = this.pointList.findIndex(item => {
					return item.pointId == data.point.id
				})
				if(index != -1) {
					this.searchFactor.pointIndexs = [index]
					this.changePoint()
				}
			})
		},
		watch: {
			projectInfo() {
				this.initData();
				this.searchFactor.projectId = this.projectInfo.id;
				this.initDeviceList();
			},
			activeName() {
				if(this.activeName == 'first') {
					this.queryData()
  				}
			},
			'$route'(){
				this.initDeviceList();
			},
			secondRouters(){
				this.initDeviceList();
			}
		},
		methods: {
			handleCurrentChange(page){
				this.page = page;
				this.queryData();
			},
			closeConnect() {
				if(this.scoketConnect){
					this.scoketConnect.clearSend();
					this.scoketConnect.closeConnect();
				}
				this.clearTime();
			},
			closeWindow(index) {
				this.chartList.splice(index, 1)
				this.$nextTick(() => {
					this.chartList.forEach((item, index) => {
						this.initChart(item, index)
					})
				})
			},
			showWindow(item,index) {
				this.chartList.forEach(it => {
					it.zIndex = 0;
					it.width = 24
				})
				item.width = 24;
				item.zIndex = 999
				this.chartHeight = 'calc(100vh - 200px)'
				this.layout = 'absolute'
				this.$nextTick(()=>{
					this.$refs['chartRef'+index][0].resize();
				})
			},
			restoreWindow(item,index) {
				this.chartList.forEach(it => {
					it.zIndex = 0;
					it.width = 12
				})
				this.chartHeight = '280px'
				this.layout = 'relative'
				this.$nextTick(()=>{
					this.$refs['chartRef'+index][0].resize();
				})
			},
			// 标记异常点start=========
			updateShowStatus(pointId) {
				let status = this.getPointStatus(pointId) == 'show' ? 'hidden' : 'show';
				localStorage.setItem('showStatus_' + pointId, status)
				this.hiddenMenu()
				this.chartList.forEach((item, index) => {
					if(this.searchFactor.type == 0) {
						this.initChart(item, index)
					} else {
						this.muliChart(item, index)
					}
				})
			},
			getPointStatus(pointId) {
				let status = localStorage.getItem('showStatus_' + pointId)
				return status || 'show'
			},
			updateStatusSingle(updateData,dataList){
				let states=[],
						status = this.dataStatus,
						startTime =updateData.dataList[updateData.startValue][0],
						endTime =updateData.dataList[updateData.endValue][0]
						dataList.forEach(item=>{
							if(item[1]>=updateData.minValue&&item[1]<=updateData.maxValue){
								states.push({
									data_id: updateData.data_id,
							data_time: item[0],
							phy: updateData.phyId,
							state: status
								})
							}
						})
						if(states.length){
							this.updateDataStatus({
								startTime:startTime,
								endTime:endTime,
								states:states
							})
						}
			},
			updateStatusMuli(updateData){
				let chartInfo = this.chartList[updateData.chartIndex],
					startTime = chartInfo.times[updateData.startValue],
						endTime = chartInfo.times[updateData.endValue]
				chartInfo.lineList.forEach(item=>{
					let dataList = item.datas.filter(item=>{
						if(new Date(item[0])>=new Date(startTime)&&new Date(item[0])<=new Date(endTime)){
							return item
						}
					})
					this.updateStatusSingle({...{
						dataList:item.datas,
						data_id:item.data_id,
					},...updateData},dataList)
				})
			},
			saveOperateValue(){
				let updateData = this.updateData;
				if(updateData.isMuli){
					this.updateStatusMuli(updateData)
				}else{
					let dataList = updateData.dataList.slice(updateData.startValue,updateData.endValue+1)
					this.updateStatusSingle(updateData,dataList)
				}
				
			},
			updateStatus() {
				let currentParams = this.currentParams,
					status = currentParams.status == '0' ? '1' : '0',
					startTime = currentParams.data_time;
				let states = [{
					data_id: currentParams.data_id,
					data_time: startTime,
					phy: currentParams.phyId,
					state: status
				}]
				this.updateDataStatus({
					startTime: startTime,
					endTime: startTime,
					states: states
				})
			},
			updateDataStatus(sendData) {
				sendData.pointIds = this.searchFactor.pointIds
				this.$httpEs.post("/line/editLineStates", sendData).then(data => {
					this.showStatusModal = false;
					this.queryData();
				})
			},
			// 标记异常点end=========
			clearTime() {
				Object.keys(this.interObj).forEach(item => {
					clearInterval(this.interObj[item])
				})
				this.interObj = {};
			},
			connect(deviceIds) {
				// 铁三院数据不需要webscoket 反之后续需要，先屏蔽掉
				return
				if(this.searchFactor.type == '1') { //如果是历史状态 不链接
					return
				}
				if(this.scoketConnect) {
					//清除定时器
					this.clearTime()
					this.scoketConnect.connect(deviceIds.toString());
				} else {
					this.scoketConnect = new util.scoketConnect({
						pointIds: deviceIds.toString(),
						pushType: 0
					})
				}
			},
			addLineData(itemList) {
				if(this.searchFactor.type!="0"){return}//实时数据才新增
				//更新数据
				let item = itemList[0],
					phy = item.phy
				let chartIndex = this.chartList.findIndex(i => {
					return i.phyId == phy && i.dataId == item.data_id
				})
				if(chartIndex != -1) {
					return
				}
				let charts = this.$refs['chartRef' + chartIndex][0].getCharts();
				let option = charts.getOption();
				let dataList = option.series[0].data,
					timeList = option.xAxis[0].data;
				if(dataList.length > 1023) {
					dataList.splice(0, itemList.length);
					timeList.splice(0, itemList.length);
				}
				itemList.forEach(it => {
					dataList.push([it.data_time, it.data, it.status])
					timeList.push(it.data_time)
				})
				if((item.dataId + phy) == this.fftPhyId) {
					this.fftArr = dataList;
				}
				option.series[0].data = dataList;
				option.yAxis[0].max = util.getMax;
				option.yAxis[0].min = util.getMin;
				option.xAxis[0].data = timeList
				this.chartList[chartIndex].newOptions = option
				this.$forceUpdate()
			},
			muliChart(item,index) {
				let series = [],
					singleArr = [],
					timeArr = item.times,
					legendArr = [];
				let effectObj = {},
					effectSeries = [];
				item.lineList.forEach((it, idx) => {
					legendArr.push(it.pointName)
					let showStatus = this.getPointStatus(it.pointId)
					let dataArr = JSON.parse(JSON.stringify(it.datas))
					if(showStatus == 'hidden') { //如果是隐藏异常点
						let newDatas = [];
						dataArr.forEach(it => {
							if(it[2] == '0') {
								newDatas.push(it);
							}
						});
						dataArr = newDatas;
					} else {
						dataArr.forEach(it => {
							if(it[2] > 0) { //异常点
								effectObj[it[2]] = effectObj[it[2]] || []
								effectObj[it[2]].push(it)
							}
						})
						
					}
					let sigArr = dataArr.map(it => {
						return it[1]
					})
					singleArr = singleArr.concat(sigArr)
					series.push({
						name: it.pointName,
						type: 'line',
						smooth: true, //折线图平滑
						data: it.datas,
						barMaxWidth: 30,
						symbol: 'circle',
						sampling: 'average',
						symbolSize: 5,
						showSymbol: false,
						lineStyle: {
							normal: {
								width: 1
							}
						},
						itemStyle: {
							normal: {
								color: util.colors3[idx % util.colors.length],
								borderColor: util.colors4[idx % util.colors.length],
								borderWidth: 12
							}
						}
					})
				})
				Object.keys(effectObj).forEach(it => {
					effectSeries.push({
						name: '数据值',
						type: 'effectScatter',
						color: this.statusColor[it],
						symbolSize: 3,
						data: effectObj[it]
					})
				})
				let opts = {
					title: [{
						text: item.phyName + "(" + item.lineList[0].unit + ")",
						subtext: '',
						x: 'center',
						y: 'top',
						textAlign: 'left',
						top: 5,
						itemGap: 5,
						textStyle: {
							fontStyle: "normal",
							fontWeight: "normal",
							fontFamily: "sans-serif",
							fontSize: 14
						}
					}],
					toolbox:{
						x:20,
						feature: {
							brush: {
								type: ['rect'],
								title: {
									rect: '圈选更改数据'
								}
							}
						}
					},
					brush: {
						toolbox:['rect'],
						throttleType:'debounce',
						throttleDelay:1000,
						xAxisIndex:0
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						},
						formatter: (params, ticket, callback) => {
							let str = params[0].name + "</br>"
							params.forEach((it, idx) => {
								if(it.seriesName != "数据值") {
									str += "<div style='background:" +it.color + "' class='tip_ring fl'></div><div class='fl' style='min-width:180px;'>" + it.seriesName + " 值:" + it.value[1] + "</div>"
									if(idx % 2 == 1) {
										str += '</br>'
									}
								}
							})
							return str;
						},
						confine:true
					},
					grid: {
						left: 10,
						right: 10,
						bottom: 10,
						top: 50,
						containLabel: true
					},
					legend: {
						type: 'scroll',
						data: legendArr,
						top: 25
					},
					dataZoom: [{
						type: 'inside',
						realtime: true
					}],
					xAxis: [{
						data: util.getTimes(series),
						axisLabel: {
							formatter: function(val) {
								return val.split(" ").join("\n");
							},
							showMaxLabel: true //展示x轴最后一条数据
						},
						axisTick: {
							inside: true,
							lignWithLabel: true //这两行代码可以让刻度正对刻度名
						},
						boundaryGap: false, //两边是否留白
						axisLine: {
							onZero: false, //刻度线不展示在0刻度上
						}
					}],
					yAxis: [{
						min: util.getMin,
						max: util.getMax,
						type: 'value',
						scale: true,
						precision: 2,
						axisLabel: {
							showMaxLabel:false,
							showMinLabel:false
						},
						axisTick: {
							show: false
						}
					}],
					series: series.concat(effectSeries)
				};
				item.newOptions = opts;
				this.$forceUpdate();
				this.$Bus.$on('click'+index, (ev, s) => {
					let info = this.pointList.find(info => {
						if(ev.seriesName != "数据值") {
							return info.pointName == ev.seriesName
						}
					})
					if(!info) {
						return
					}
					this.currentParams = {
						pointId: info.pointId,
						pointName: info.pointName,
						dataTime: ev.data[0],
						phyId: item.phyId,
						data_time: ev.data[0],
						data_id: info.deviceId,
						status: ev.data[2],
						chartData: item,
						chartIndex:index
					}
					this.showMenu(ev)
				})
				this.$Bus.$on('brushSelected'+index,(params) =>{
					this.$nextTick(()=>{
						if(params.batch[0].areas[0]){
							let coordRanges = params.batch[0].areas[0].coordRanges[0],
								startValue = coordRanges[0][0],
								endValue = coordRanges[0][1],
								minValue = coordRanges[1][0],
								maxValue = coordRanges[1][1]
							this.updateData={
								startValue:startValue,
								endValue:endValue,
								minValue:minValue,
								maxValue:maxValue,
								isMuli:true,
								chartIndex:index,
								phyId:item.phyId
							}
							this.showStatusModal = true;
						}
					})
				});
			},
			initChart(item, idx) { //一个物理量一个chart
				let showStatus = this.getPointStatus(item.pointId)
				let datas = JSON.parse(JSON.stringify(item.datas))
				if(showStatus == 'hidden') { //如果是隐藏异常点
					let newDatas = [];
					datas.forEach(it => {
						if(it[2] == '0') {
							newDatas.push(it);
						}
					});
					datas = newDatas;
				}
				let timeArr = datas.map(it => {
					return it[0]
				})
				let effectObj = {},
					effectSeries = [];
				datas.forEach(it => {
					if(it[2] > 0) { //异常点
						effectObj[it[2]] = effectObj[it[2]] || []
						effectObj[it[2]].push(it)
					}
				})
				Object.keys(effectObj).forEach(it => {
					effectSeries.push({
						name: '数据值',
						type: 'effectScatter',
						color: this.statusColor[it],
						symbolSize: 3,
						data: effectObj[it]
					})
				})
				let config = util.getConfig(datas)
				let option = {
					title: {
						text: item.pointName + "(" + item.manuId + ')过程曲线',
						x: 'center',
						y: 'top',
						top: 5,
						itemGap: 5,
						textStyle: {
							fontStyle: "normal",
							fontWeight: "normal",
							fontFamily: "sans-serif", //字体系列
							fontSize: 12, //字体大小left
						}
					},
					toolbox: {
						x: 20,
						show: true,
						feature: {
							brush: {
								type: ['rect'],
								title: {
									rect: '圈选更改数据'
								}
							}
						}
					},
					brush: {
						toolbox: ['rect'],
						throttleType: 'debounce',
						throttleDelay: 1000,
						xAxisIndex: 0,
						seriesIndex: 0,
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						},
						formatter: (params, ticket, callback) => {
							let obj = params[0]
							let str = ""
							let singleArr = []
							datas.filter(it => {
								if(it[2] == 0) {
									singleArr.push(it[1])
								}
							})
							if(singleArr.length == 0) {
								singleArr = [0];
							}
							let avg = function() { //平均值
								let sum = singleArr.reduce((acc, cur) => {
									return acc + cur
								})
								return(sum / singleArr.length).toFixed(3);
							}()
							str += "<div style='min-width:150px;'>" + obj.name + "：" + obj.data[1] + "</div>"
							str += "<div style='min-width:150px;float:left;margin-right:5px'>" + "最大值：" + Math.max(...singleArr).toFixed(2) + "</div>"
							// str += "<div style='min-width:150px;float:left;margin-right:5px'>" + "数据状态：" + util.statusObj[obj.data[2]] + "</div></br>"
							str += "<div style='min-width:150px;float:left;margin-right:5px'>" + "最小值：" + Math.min(...singleArr).toFixed(2) + "</div>"
							str += "<div style='min-width:150px;float:left;margin-right:5px'>" + "平均值：" + avg + "</div></br>"
							return str;
						},
						position: function(point, params, dom, rect, size) {
							//其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
							var x = point[0]; //
							var y = point[1];
							var boxWidth = size.contentSize[0];
							var boxHeight = size.contentSize[1];
							var posX = 0; //x坐标位置
							var posY = 0; //y坐标位置

							if(x < boxWidth) { //左边放不开
								posX = 5;
							} else { //左边放的下
								posX = x - boxWidth - 5;
							}

							if(y < boxHeight) { //上边放不开
								posY = 5;
							} else { //上边放得下
								posY = y - boxHeight - 5;
							}
							return [posX, posY];
						}
					},
					dataZoom: [{
						type: 'inside', //鼠标滚轮
						realtime: true,
					}],
					xAxis: {
						data: timeArr,
						axisLabel: {
							show: true,
							formatter: function(val) {
								return val.split(" ").join("\n");
							},
							showMaxLabel: true //展示x轴最后一条数据
						},
						axisLine: {
							show: true,
							onZero: false //刻度线不展示在0刻度上
						},
						axisTick: {
							show: true,
							inside: true,
							lignWithLabel: true //这两行代码可以让刻度正对刻度名
						},
						boundaryGap: true, //两边是否留白
					},
					grid: {
						left: 30,
						right: 40,
						bottom: 10,
						top: 30,
						containLabel: true
					},
					yAxis: {
						type: 'value',
						max: util.getMax,
						min: util.getMin,
						scale: true, //坐标刻度不会强制包含零刻度
						name: (item.phyName || '') + "(" + item.unit + ")",
						nameLocation: 'center',
						nameGap: util.getNameGap(config.maxXAxis), // 坐标轴名称与轴线之间的距离
						precision: 2,
						splitNumber: 5, //分成5个刻度
						nameTextStyle: { //文字样式
							fontSize: 12
						},
						axisLabel: {
							showMaxLabel:false,
							showMinLabel:false
						},
						axisTick: {
							inside: false,
							show: false

						}
					},
					series: [{
						name: '',
						type: 'line',
						data: datas,
						hoverAnimation: false,
						showSymbol: false,
						symbol: 'circle',
						symbolSize: 10
					}].concat(effectSeries)
				};
				item.newOptions = option;
				this.$forceUpdate();
				this.$Bus.$on('click'+idx, (ev, s) => {
					let pointId = this.pointList.find(info => {
						return info.deviceId == item.dataId
					}).pointId
					this.currentParams = {
						pointId: pointId,
						pointName: item.pointName,
						dataTime: ev.name,
						phyId: item.phyId,
						data_time: ev.data[0],
						data_id: item.dataId,
						status: ev.data[2],
						chartData: item,
						chartIndex:idx
					}
					this.showMenu(ev)
				})
				this.$Bus.$on('brushselected'+idx, (params) => {
					this.$nextTick(() => {
						if(params.batch[0].areas[0]) {
							let coordRanges = params.batch[0].areas[0].coordRanges[0],
								startValue = coordRanges[0][0],
								endValue = coordRanges[0][1],
								minValue = coordRanges[1][0],
								maxValue = coordRanges[1][1]
							this.updateData = {
								startValue: startValue,
								endValue: endValue,
								minValue: minValue,
								maxValue: maxValue,
								dataList: item.datas,
								data_id: item.dataId,
								phyId: item.phyId
							}
							this.showStatusModal = true;
						}
					})
				});
			},
			//初始化数据
			initData() {
				this.searchFactor = {
					projectId: '',
					pointIds: [],
					deviceIds: [],
					type: '0',
					pageSize: 500,
					modify_start_time: '',
					modify_end_time: ''
				}
				this.searchFactor.pageSize = localStorage.getItem('pageSize_' + this.projectInfo.id) || 500
				this.pointList = [];
				this.initInfo = {
					product: {}
				}
				this.chartList = [];
			},
			initDeviceList() {
				let  factorInfo = this.getFactorInfo();
				let points = factorInfo.points,
					pointObj = {}
				points.forEach(item=>{
					pointObj[item.id] = item.name;
				})
				this.searchFactor.pointIndexs = [];
				this.pointList = [];
				this.$httpProj.get("/point/point/getPointNamesByPointIds?pointIds="+Object.keys(pointObj).toString()).then(data=>{
					this.searchFactor.deviceIds = []
					data.data.forEach(item => {
						item.id = item.pointId;
						item.pointName = pointObj[item.id]||''
					})
					this.pointList = data.data;
					if(data.data[0]) {
						this.searchFactor.pointIndexs = [0];
						this.changePoint()
					}
				})
			},
			
			getFactorInfo(){
				let {index,index2} = this.$route.params
				let factorInfo = this.secondRouters[index]
				if(index!=undefined&&index2!='first'){
					factorInfo = this.secondRouters[index].children[index2]
				}
				return factorInfo
			},
			changePoint() {
				this.searchFactor.pointIds = []
				this.searchFactor.deviceIds = []
				this.selectPointList = [];
				this.searchFactor.pointIndexs.forEach(item => {
					let point = this.pointList[item]
					this.selectPointList.push(point)
					this.searchFactor.pointIds.push(point.pointId)
					this.searchFactor.deviceIds.push(point.deviceId);
					this.initInfo.freq = point.frequency; //测点改成多选，默认选择最后一个测点的采集频率
				})
				this.clearTime()
				this.queryData()
			},
			changeQueryType(type) {
				if(type == 1) {
					this.closeConnect();
				}
				this.changePoint();
			},
			muliPrevOrNext(type, item, chartIndex) {
				let charts = this.$refs['chartRef' + chartIndex][0].getCharts();
				let option = charts.getOption();
				let timeArr = option.xAxis[0].data;
				let startTime = "*",
					endTime = "*",
					sTime = timeArr[0],
					eTime = timeArr[timeArr.length - 1],
					timeOrder = "desc"
				if(type == 'prev') {
					endTime = sTime;
				} else {
					startTime = eTime;
					timeOrder = 'asc'
				}
				startTime = startTime.replace(' ', "T")
				endTime = endTime.replace(' ', "T")
				let dateTime = " AND data_time:[" + startTime + " TO " + endTime + "]"
				let query = '';
				let deviceIds = this.getPageDeviceIds()
				deviceIds.forEach((item, index) => {
					if(index == 0) {
						query += 'data_id:' + item
					} else {
						query += ' OR data_id:' + item
					}
				})
				let param = {
					includes: [item.phyId],
					query: "(" + query + ")" + dateTime,
					pageSize: this.searchFactor.pageSize,
					timeOrder: timeOrder
				}
				this.$httpEs.post("/line/queryLineResult", param).then(data => {
					if(data.data.length) {
						let times = [],
							effectSeries = [];
						let effectObj = {}
						data.data.forEach((it, index) => {
							let point = this.pointList.find(i => {
								return i.deviceId == it.dataId
							})
							let showStatus = this.getPointStatus(point.pointId)
							let datas = JSON.parse(JSON.stringify(it.datas))
							if(showStatus == 'hidden') { //如果是隐藏异常点
								let newDatas = [];
								datas.forEach(it => {
									if(it[2] == '0') {
										newDatas.push(it);
									}
								});
								datas = newDatas;
							} else {
								datas.forEach(it => {
									if(it[2] > 0) { //异常点
										effectObj[it[2]] = effectObj[it[2]] || []
										effectObj[it[2]].push(it)
									}
								})
								
							}
							option.series.forEach(i => {
								let point = this.pointList.find(i => {
									return i.deviceId == it.dataId
								})
								if(i.name == point.pointName) {
									i.data = datas
								}
							})
							let timeArr = it.datas.map(i => {
								return i[0]
							}) //用it.datas 不然回退不了
							times = times.concat(timeArr)
							times = times.sort();
						})
						Object.keys(effectObj).forEach(it => {
							effectSeries.push({
								name: '数据值',
								type: 'effectScatter',
								color: this.statusColor[it],
								symbolSize: 3,
								data: effectObj[it]
							})
						})
						option.yAxis[0].max = util.getMax
						option.yAxis[0].min = util.getMin
						option.xAxis[0].data = times
						this.chartList[chartIndex].newOptions = option;
						this.$forceUpdate();
					}
				})
			},
			prevOrNextClick(type, item, chartIndex) {
				if(this.searchFactor.type == 1) {
					this.muliPrevOrNext(type, item, chartIndex)
					return
				}
				let charts = this.$refs['chartRef' + chartIndex][0].getCharts(),
					option = charts.getOption();
				let timeArr = option.xAxis[0].data;
				let startTime = "*",
					endTime = "*",
					sTime = timeArr[0],
					eTime = timeArr[timeArr.length - 1],
					timeOrder = "desc"
				if(type == 'prev') {
					endTime = sTime;
				} else {
					startTime = eTime;
					timeOrder = 'asc'
				}
				startTime = startTime.replace(' ', "T")
				endTime = endTime.replace(' ', "T")
				let dateTime = " AND data_time:[" + startTime + " TO " + endTime + "]"
				let param = {
					includes: [item.phyId],
					query: 'data_id:' + item.dataId + dateTime,
					pageSize: this.searchFactor.pageSize,
					timeOrder: timeOrder
				}
				this.$httpEs.post("/line/queryLineResult", param).then(data => {
					if(data.data.length) {
						this.reloadChart(data.data[0], chartIndex)
					}
				})
			},
			reloadChart(obj, chartIndex) {
				let point = this.pointList.find(i => {
					return i.deviceId == obj.dataId
				})
				let showStatus = this.getPointStatus(point.pointId)
				let effectSeries = [];
				if(showStatus == 'hidden') {
					let newDatas = [];
					obj.datas.forEach(it => {
						if(it[2] == 0) {
							newDatas.push(it)
						}
					})
					obj.datas = newDatas;
				} else {
					let effectObj = {}
					obj.datas.forEach(it => {
						if(it[2] > 0) { //异常点
							effectObj[it[2]] = effectObj[it[2]] || []
							effectObj[it[2]].push(it)
						}
					})
					Object.keys(effectObj).forEach(it => {
						effectSeries.push({
							name: '数据值',
							type: 'effectScatter',
							color: this.statusColor[it],
							symbolSize: 3,
							data: effectObj[it]
						})
					})
				}
				let timeArr = obj.datas.map(item => {
					return item[0];
				})
				let charts = this.$refs['chartRef' + chartIndex][0].getCharts();
				let options = charts.getOption();
				options.series[0].data = obj.datas;
				options.series = options.series.concat(effectSeries)
				options.yAxis[0].max = util.getMax
				options.yAxis[0].min = util.getMin
				options.xAxis[0].data = timeArr
				this.chartList[chartIndex].newOptions = options;
				this.$forceUpdate()
			},
			getPageDeviceIds(){
				return this.searchFactor.deviceIds.slice((this.page-1)*this.size,this.page*this.size)
			},
			queryData() {
				localStorage.setItem('pageSize_' + this.projectInfo.id, this.searchFactor.pageSize)
				let searchFactor = this.searchFactor;
				let sTime = new Date(searchFactor.modify_start_time).getTime()
				let eTime = new Date(searchFactor.modify_end_time).getTime()
				if(sTime && eTime && eTime < sTime) {
					this.$message({
						message: "结束时间不能小于开始时间",
						type: "warning"
					})
					return
				}
				if(this.activeName == 'second') {
					this.$nextTick(() => {
						this.$refs.gridChart.render();
					})
					return
				}
				if(!this.searchFactor.pointIds.length) {
					this.chartList = [];
					return
				}
				let startTime = searchFactor.modify_start_time || "",
					endTime = searchFactor.modify_end_time || "",
					dateTimeStr = '';
				if((startTime || endTime) && searchFactor.type == 1) { //历史监控加上时间
					startTime = startTime ? startTime.replace(" ", 'T') : "*"
					endTime = endTime ? endTime.replace(" ", 'T') : "*"
					dateTimeStr = " AND data_time:[" + startTime + " TO " + endTime + "]"
				}
				let query = '';
				let deviceIds = this.getPageDeviceIds()
				deviceIds.forEach((item, index) => {
					if(index == 0) {
						query += 'data_id:' + item
					} else {
						query += ' OR data_id:' + item
					}
				})
				let param = {
					includes: util.phyList,
					query: "(" + query + ")" + dateTimeStr,
					pageSize: this.searchFactor.pageSize
				}
				this.chartList = [];
				this.$httpEs.post("/tiesan/queryTiesanResult", param).then(data => {
					data.data.forEach(item => {
						let point = this.pointList.find(it => {
							return it.deviceId == item.dataId
						})
						item.needFFT = point.moduleType == '3' ? true : false; //3与31为动态，其他为静态设备
						item.pointName = point.pointName
						item.pointId = point.id
						item.manuId = point.manuId;
						item.zIndex = 0;
						item.width = 12
					})
					this.chartHeight = "280px"
					this.layout = "relative"
					if(this.searchFactor.type == 1) {
						let chartObj = {}
						data.data.forEach((it, index) => {
							chartObj[it.phyId] = chartObj[it.phyId] || {}
							chartObj[it.phyId].phyName = it.phyName
							chartObj[it.phyId].phyId = it.phyId
							chartObj[it.phyId].phy = it.phy
							chartObj[it.phyId].unit = it.unit
							chartObj[it.phyId].lineList = chartObj[it.phyId].lineList || []
							chartObj[it.phyId].lineList.push({
								datas: it.datas,
								unit: it.unit,
								phyId: it.phyId,
								phy: it.phy,
								pointName: it.pointName,
								pointId: it.pointId
							})
							chartObj[it.phyId].times = chartObj[it.phyId].times || []
							let timeArr = it.datas.map(i => {
								return i[0]
							})
							chartObj[it.phyId].times = chartObj[it.phyId].times.concat(timeArr)
							chartObj[it.phyId].times = chartObj[it.phyId].times.sort();
						})
						Object.keys(chartObj).forEach((item, index) => {
							this.chartList.push(chartObj[item])
						})
						this.$nextTick(() => {
							this.chartList.forEach((item, index) => {
								item.newOptions = null;
								this.muliChart(item,index)
							})
						})
					} else {
						this.chartList = data.data;
						this.$nextTick(() => {
							this.chartList.forEach((item, index) => {
								item.newOptions = null
								this.initChart(item, index)
							})
						})
						this.connect(deviceIds)
					}

				})
			},
			hiddenMenu() {
				let menu = this.$el.getElementsByClassName("menuuu_box")[0]
				menu.style.display = "none";
				this.showModal2 = false;
			},
			showMenu(ev) {
				let menu = this.$el.getElementsByClassName("menuuu_box")[0],
					pageX = ev.event.event.clientX,
					pageY = ev.event.event.clientY;
				if(pageX + 200 > menu.parentElement.clientWidth) {
					pageX = pageX - 200
				}
				if(pageY + 50 > menu.parentElement.clientHeight) {
					pageY = pageY - 50
				}
				menu.style.left = pageX - 180 + 'px';
				menu.style.top = pageY + 'px';
				menu.style.display = "block";
				this.showModal2 = true;
			}
		}
	};
</script>